package com.fs.console.base.utils;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fs.common.pojo.Company;
import com.fs.console.base.interceptor.AuthenticationInterceptor;
import com.fs.console.base.param.SysConstant;
import com.fs.console.base.vo.LoginUser;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ACE
 * @desc 系统应用工具
 * @creationTime 2019-02-28 14:37
 * @projectName gps-root
 * @packageName com.fs.base.utils
 */
public class ApplicationUtils {
    @Autowired @Getter @Setter
    private static ApplicationContext ctx;

    /**
     * 根据当前request获取token并从中获取userId
     * @return
     */
    public static String getUserId(){
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isBlank(token)){
            return null;
        }
        return decryptToken(token).get(0);
    }

    /**
     * token解密
     * @param token
     * @return
     */
    public static List<String> decryptToken(String token){
        return JWT.decode(token).getAudience();
    }

    /**
     * 加密用户id为token
     * @param user
     * @return
     */
    public static String getToken(LoginUser user) {
        String token="";
        token= JWT.create().withAudience(String.valueOf(user.getUser().getId()),
                DateUtil.format(new Date(), SysConstant.DATA_DORMAT))
                .sign(Algorithm.HMAC256(user.getUser().getPwd()));
        return token;
    }

    /**
     * 加密字符串为token,不包含签名
     * @param str
     * @return
     */
    public static String getToken(String str) {
        String token="";
        token= JWT.create().withAudience(String.valueOf(str),
                DateUtil.format(new Date(), SysConstant.DATA_DORMAT))
                .sign(Algorithm.HMAC256(str));
        return token;
    }
    /**
     * 根据当前request获取token
     * @return
     */
    public static String getToken(){
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        if(StringUtils.isBlank(token)){
            return "";
        }
        return token;
    }
    /**
     * 获取当前Request
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getRequest();
    }

    /**
     * 获取当前Session
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession(true);
    }

    /**
     * 获取springBean对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return ctx.getBean(beanName);
    }

    /**
     * 获取所有请求参数及参数值
     * @return
     */
    public static Map<String, Object> getRequestDatas(String... searchType) {
        Map<String, Object> data = new HashMap<String, Object>(16);
        HttpServletRequest request = getRequest();
        Map<String, String[]> map = request.getParameterMap();
        /*System.out.println("-------");
        System.out.println(JSON.toJSONString(map));
        System.out.println("-------");*/
        Integer len = 0;
        for(String key : map.keySet()){
            String[] vArray = map.get(key);
            len = vArray.length;
            if(len==1){
                data.put(key, vArray[0]);
                if(searchType!=null && searchType.length>0){
                    data.put(key.concat("_searchType"),searchType[0]);
                }
            }else if(len>1){
                data.put(key, vArray);
            }else{
                continue;
            }
        }
        return data;
    }

    /**
     * request数据转java对象
     * @param class1
     * @return
     */
    public static Object requestData2Bean(Class<?> class1) {
        Map<String, Object> map = getRequestDatas();
        String json = JSON.toJSONString(map);
        return JSON.parseObject(json, class1);
    }

    public static Boolean isSuperAdmin(){
        boolean flag = false;
        LoginUser user = getUser();
        if(user!=null && user.getUser().isSysAdm()){
            flag = true;
        }
        return flag;
    }

    /**
     * 获取session用户信息
     * @return
     */
    public static LoginUser getUser (){
        String userId = getUserId();
        LoginUser vo = AuthenticationInterceptor.loginUserMap.get(userId);
        return vo;
    }

    /**
     * 获取session部门信息
     */
    public static List<Company> getCompanyList(){
        String userId = getUserId();
        List<Company> list = AuthenticationInterceptor.userCompanyMap.get(userId);
        return list;
    }

    /** 获取url地址 */
    public static String getCurUrl() {
        HttpServletRequest request = getRequest();
        String url = request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort();
        return url;
    }

    /** 获取ip地址 */
    public static String getRemoteHost(){
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    /**
     * 获取当前登录用户菜单按钮信息
     * @return
     */
    public static String getMenuMotions (){
        HttpSession session = getRequest().getSession();
        return String.valueOf(session.getAttribute(SysConstant.SESSION_CONSOLE_MENU_MOTION));
    }
}
